//
//  LNOAuthViewController.swift
//  727-黑马08微博-测试
//
//  Created by apple on 15/7/30.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

class LNOAuthViewController: UIViewController , UIWebViewDelegate{
    
//    MARK:搭建界面
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
//    关闭界面
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        view.backgroundColor = UIColor.whiteColor()
//        print(view.backgroundColor)
//        加载授权页面
        webView.loadRequest(NSURLRequest(URL: LNNetworkTools.sharedTools.oauthUrl()))
        
    }
//    MARK: - UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
//        print("开始")
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
//        print("结束")
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
//        判断是否包含回调地址
        if !urlString.hasPrefix(LNNetworkTools.sharedTools.redirectUri) {
            return true
        }

        
        if let query = request.URL?.query where query.hasPrefix("code=") {

//            从query中获取授权码
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            print("获取授权码" + code)
//            print(code)
//            TODO:换取TOKEN
            loadAccessToken(code)
        } else {
            close()
        }
//        print("取消")
        
        return false
    }
    
    private func loadAccessToken(code: String) {
        LNNetworkTools.sharedTools.loadAccessToken(code) {(result, error) -> () in
            if error != nil || result == nil {
                self.netError()
                return
            }
//           字典转模型
//            1.用token获取的信息创建用户账户模型
//            2.异步加载用户信息，保存用户信息(模型中完成)
            
            LNUserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError()
                    return
                }
                
                // 发送通知切换视图控制器
                NSNotificationCenter.defaultCenter().postNotificationName(LNRootViewControllerSwitchNotification, object: false)
                
                // 关闭控制器（单独讲）Modal 出来的控制器，一定注意需要 dismiss!
                self.close()
            })
        }
    }
    
    deinit {
        print("88")
    }
    
    

/// 网络出错处理
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
//        延时一段时间
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1*NSEC_PER_SEC))
                        dispatch_after(when, dispatch_get_main_queue()) {
                            self.close()
    }

}



}





























